/**
 * @program: My Application
 * @description: ...
 * @author: Yumaoo
 * @create: 2024-07-03 01:34
 **/
package com.example.myapplication;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class FetchData extends AsyncTask<String, Integer, String> {
    private String baseUrl = Config.BASE_URL;
    private Context context;
    public FetchData(Context context){
        this.context=context;
    }
    @Override
    protected String doInBackground(String... params) {

        return postData();


    }

    protected void onPostExecute(String status) {

        Toast.makeText(context,status, Toast.LENGTH_LONG).show();

    }


    protected void onProgressUpdate(Integer... progress) {

    }

    public String postData() {
        // Create a new HttpClient and Post Header

        StringBuilder result = new StringBuilder();
        HttpURLConnection connection = null;

        try {
            // Create connection
            URL url = new URL(baseUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // Read response
            int status = connection.getResponseCode();
            if (status == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                reader.close();

                // Process JSON and update database
                String json = result.toString();
                Log.d("Fetch Data", json);
                JSONArray buildings = new JSONArray(json);
                DatabaseHelper db = new DatabaseHelper(context);
                db.updateDatabase(buildings);

                return "Db Updated";
            } else {
                throw new IOException("Unexpected status code: " + status);
            }
        } catch (IOException | JSONException e) {
            Log.e("Network Error", "Error fetching data", e);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        return "Error";


    }

}
